package com.base.cn.platform.os.service.qa.record;

import com.base.cn.platform.os.common.mybatis.Pagination;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.dao.qa.record.QaGainAttendRecordDao;
import com.base.cn.platform.os.entity.qa.question.QaQuestion;
import com.base.cn.platform.os.entity.qa.question.QuestionCondition;
import com.base.cn.platform.os.entity.qa.record.QaGainAttendRecord;
import com.base.cn.platform.os.service.manage.teacher.SysTeacherService;
import com.base.cn.platform.os.service.manage.user.account.CusUserAccountService;
import com.base.cn.platform.os.service.manage.user.user.CusUserService;
import com.base.cn.platform.os.service.qa.question.QaQuestionBiz;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 围观收益记录Biz
 * @author LIZHIPENG
 * @since 2018/5/2
 */
@Service
public class QaGainAttendRecordBiz extends QaRecordBaseBiz<QaGainAttendRecord, QaGainAttendRecordDao> {

    @Autowired
    private QaQuestionBiz qaQuestionBiz;
    @Autowired
    private SysTeacherService sysTeacherService;
    @Autowired
    private CusUserService cusUserService;
    @Autowired
    private CusUserAccountService cusUserAccountService;
    @Autowired
    private  QaGainAttendRecordDao qaGainAttendRecordDao;

    /**
     * 查询旁听分成收益数量
     * @param gainAttendRecord 查询条件
     * @return 数量
     */
    public BigDecimal getGainAttenRecordCount(QaGainAttendRecord gainAttendRecord){
        String whereSql = getWhereSql(gainAttendRecord);
        return this.count(whereSql);
    }

    /**
     * 生成旁听支付记录
     * @param gainAttendRecordList
     */
    public void addGainAttendRecord(List<QaGainAttendRecord> gainAttendRecordList){
        this.batchSave(gainAttendRecordList);
    }

    /**
     * 分页查询旁听收益记录
     * @param page 分页
     * @param gainAttendRecord 条件
     * @param questionData 是否设置问题数据：true：是，false:否
     * @param userData 是否设置用户数据：true：是，false:否
     * @return
     */
    public PageInfo<QaGainAttendRecord> queryGainAttendRecordListPage(Pagination page, QaGainAttendRecord gainAttendRecord, boolean questionData, boolean userData){
        String whereSql = getWhereSql(gainAttendRecord);
        PageInfo<QaGainAttendRecord> gainAttendRecordPageInfo = this.findPage(whereSql, page, null);
        gainAttendRecordPageInfo.setList(this.setExtendData(gainAttendRecordPageInfo.getList(), questionData, userData));
        return gainAttendRecordPageInfo;
    }

    /**
     * 查询用户问答收益总额
     * @param qaGainAttendRecord 查询条件
     * @return 总收益
     */
    public double getUserQaEarning(QaGainAttendRecord qaGainAttendRecord){
        List<QaGainAttendRecord> qaGainAttendRecordList = this.queryGainAttendRecordList(qaGainAttendRecord, false, false);
        BigDecimal sumPrice = new BigDecimal(0);
        if(ObjectUtils.isNotEmpty(qaGainAttendRecordList)){
            for (QaGainAttendRecord gainAttendRecord : qaGainAttendRecordList) {
                sumPrice = sumPrice.add(new BigDecimal(gainAttendRecord.getAmount().toString()));
            }
        }
        return sumPrice.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    /**
     * 查询围观收益记录列表（不分页）
     * @param gainAttendRecord 查询条件
     * @param questionData 是否设置问题数据：true：是，false:否
     * @param userData 是否设置用户数据：true：是，false:否
     * @return List<QaGainAttendRecord>
     */
    public List<QaGainAttendRecord> queryGainAttendRecordList(QaGainAttendRecord gainAttendRecord, boolean questionData, boolean userData){
        String whereSql = getWhereSql(gainAttendRecord);
        List<QaGainAttendRecord> qaGainAttendRecordList = this.find(whereSql, null, null);
        qaGainAttendRecordList = this.setExtendData(qaGainAttendRecordList, questionData, userData);
        return qaGainAttendRecordList;
    }

    /**
     * 提取收益到我的账户
     * @param qaGainAttendRecord 提取条件
     * @return Map<String, Object>
     */
    @Transactional(rollbackFor = IllegalArgumentException.class)
    public String  extractEarning(QaGainAttendRecord qaGainAttendRecord){
        List<QaGainAttendRecord> qaGainAttendRecordList = this.queryGainAttendRecordList(qaGainAttendRecord, false, false);
        if(ObjectUtils.isNotEmpty(qaGainAttendRecordList)){
            BigDecimal sumPrice = new BigDecimal(0);
            for (QaGainAttendRecord gainAttendRecord : qaGainAttendRecordList) {
                sumPrice = sumPrice.add(new BigDecimal(gainAttendRecord.getAmount().toString()));
                gainAttendRecord.setStatus(2);
            }
            cusUserAccountService.updateAccountMoney(qaGainAttendRecord.getReceiptorId(),sumPrice.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue(),"CASH","ATTEND",new BigDecimal(0),null,null,true,"CASH",new BigDecimal(0), 2);
            this.updateBatch(qaGainAttendRecordList);
            return "围观收益提取成功";
        }
        return "没有可提取的收益";
    }

    /**
     * 分页查询旁听收益记录
     * @param page 分页
     * @param gainAttendRecord 条件
     * @return
     */
    public PageInfo<QaQuestion> queryAdminGainAttendRecordListPage(Pagination page, QaGainAttendRecord gainAttendRecord){
        QuestionCondition condition =  new   QuestionCondition();
        condition.setTenantId(gainAttendRecord.getReceiptorId());
        condition.setIsFree(2);
        condition.setSelectFrom(1);
        condition.setCompleteStatus(2);
        condition.setContext(gainAttendRecord.getQuestionContext());
        PageInfo<QaQuestion> qaQuestionPageInfo = qaQuestionBiz.queryQuestionListPage(page, condition, null, true, true, true, false, false, false, false, false);
        //设置问答收益记录
        for(QaQuestion qaQuestion:qaQuestionPageInfo.getList()){
            List<HashMap<String, Object>> hashMaps = qaGainAttendRecordDao.queryQaSumAmountCount(QaGainAttendRecord.class, qaQuestion.getId());
            if(ObjectUtils.isNotEmpty(hashMaps)){
                HashMap<String, Object> hashMap = new HashMap<>();
                for (Map<String, Object> map : hashMaps) {
                    hashMap.put(map.get("userType").toString(), map.get("amount"));
                }
                qaQuestion.setEarnings(hashMap);
                hashMap =null;
            }
        }
        return qaQuestionPageInfo;
    }


    //==================== 私有方法 ====================
    /**
     * 设置扩展数据
     * @param attendRecordList
     * @param questionData
     * @param userData
     * @return
     */
    private List<QaGainAttendRecord> setExtendData(List<QaGainAttendRecord> attendRecordList, boolean questionData, boolean userData){
        if(questionData){
            attendRecordList = setQuestionData(attendRecordList, questionData);
        }
        if(userData){
            attendRecordList = setUserData(attendRecordList, userData);
        }
        return attendRecordList;
    }

    /**
     * 设置问题数据
     * @param attendRecordList
     * @param questionData
     * @return
     */
    private List<QaGainAttendRecord> setQuestionData(List<QaGainAttendRecord> attendRecordList, boolean questionData){
        List<QaGainAttendRecord> newAttendRecordList = new LinkedList<>();
        if(ObjectUtils.isNotEmpty(attendRecordList) && questionData){
            String questionIds = attendRecordList.stream().map(e -> e.getQuestionId().toString()).distinct().collect(Collectors.joining(","));
            QuestionCondition condition = new QuestionCondition();
            condition.setIds(questionIds);
            List<QaQuestion> questionList = qaQuestionBiz.findQuestionList(condition, false, false, false, false, false, false, false);
            if(ObjectUtils.isNotEmpty(questionList)){
                Map<BigDecimal, List<QaQuestion>> questionMap = questionList.stream().collect(Collectors.groupingBy(QaQuestion::getId));
                for (QaGainAttendRecord qaGainAttendRecord : attendRecordList) {
                    List<QaQuestion> qaQuestionList = questionMap.get(qaGainAttendRecord.getQuestionId());
                    if(ObjectUtils.isNotEmpty(qaQuestionList)){//去除未付款的问答记录
                        qaGainAttendRecord.setQaQuestion(qaQuestionList.get(0));
                        newAttendRecordList.add(qaGainAttendRecord);
                    }
                }
            }
        }
        return newAttendRecordList;
    }

    /**
     * 设置收益人信息
     * @param attendRecordList
     * @param userData
     * @return
     */
    private List<QaGainAttendRecord> setUserData(List<QaGainAttendRecord> attendRecordList, boolean userData){
        if(ObjectUtils.isNotEmpty(attendRecordList) && userData){
            Map<Integer, List<QaGainAttendRecord>> attendRecordListMap = attendRecordList.stream().collect(Collectors.groupingBy(QaGainAttendRecord::getUserType));
            //平台收益记录列表
            List<QaGainAttendRecord> attendRecordList_1 = attendRecordListMap.get(1);
            //讲师收益记录列表
            List<QaGainAttendRecord> attendRecordList_2 = attendRecordListMap.get(2);
            if(ObjectUtils.isNotEmpty(attendRecordList_2)){
                String teacherIds = attendRecordList_2.stream().map(e -> e.getReceiptorId().toString()).distinct().collect(Collectors.joining(","));
                Map<BigDecimal, Map<String, Object>> teacherMap = sysTeacherService.findSysTeacherToMapByIds(teacherIds, false, false, false, false, false);
                if(ObjectUtils.isNotEmpty(teacherMap)){
                    for (QaGainAttendRecord qaGainAttendRecord : attendRecordList) {
                        if(qaGainAttendRecord.getUserType() == 2){
                            qaGainAttendRecord.setReceiptorMap(teacherMap.get(qaGainAttendRecord.getReceiptorId()));
                        }
                    }
                }
            }

            String attendUserIds = attendRecordList.stream().map(e -> e.getUserId().toString()).distinct().collect(Collectors.joining(","));

            //提问用户收益列表
            List<QaGainAttendRecord> attendRecordList_3 = attendRecordListMap.get(3);
            if(ObjectUtils.isNotEmpty(attendRecordList_3)){
                String userIds = attendRecordList_3.stream().map(e -> e.getReceiptorId().toString()).distinct().collect(Collectors.joining(","));
                attendUserIds = userIds + "," + attendUserIds;
            }

            Map<BigDecimal, Map<String,Object>> userMap = cusUserService.queryCusUserMapByUserIds(attendUserIds, false, false, false, false, false, false, false);
            if(ObjectUtils.isNotEmpty(userMap)){
                if(ObjectUtils.isNotEmpty(attendRecordList_3)){
                    for (QaGainAttendRecord qaGainAttendRecord : attendRecordList_3) {
                        qaGainAttendRecord.setReceiptorMap(userMap.get(qaGainAttendRecord.getReceiptorId()));
                    }
                }
                for (QaGainAttendRecord qaGainAttendRecord : attendRecordList) {
                    qaGainAttendRecord.setUser(userMap.get(qaGainAttendRecord.getUserId()));
                }
            }
        }
        return attendRecordList;
    }


}
